package org.gokulam.cgfw.core;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.gokulam.cgfw.exceptions.GenerationException;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * Generic Template Manager. Support for multiple template engines to be added later 
 * @author Harikumar Gokulam
 *
 */
public class TemplateManager {
	private Configuration config;
	
	public TemplateManager(String path) {
		config = new Configuration();
		
		// Specify the data source where the template files come from.
		// Here I set a file directory for it:
		try {
			config.setDirectoryForTemplateLoading(new File(path));
		} catch (IOException e) {
			throw new GenerationException(e);
		}
		
		// Specify how templates will see the data-model. This is an advanced topic...
		// but just use this:
		config.setObjectWrapper(new DefaultObjectWrapper());  

	}

	public String process(String templateName, Map root) {
		StringWriter out = new StringWriter();

		try {
			Template temp = config.getTemplate(templateName);
			temp.process(root, out);
		} catch (IOException e) {
			throw new GenerationException(e);
		} catch (TemplateException e) {
			throw new GenerationException(e);
		}
		out.flush(); 
		
		return out.toString();
	}
	
}
